package com.chen.palmar.common.widget.dialog;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.chen.palmar.R;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.entity.ShareEntity;
import com.primb.androidlibs.net.exception.ApiException;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


import me.shaohui.bottomdialog.BaseBottomDialog;

import static com.chen.palmar.common.constant.AppConstant.APP_WX_ID;
import static com.tencent.mm.sdk.platformtools.Util.bmpToByteArray;


/**
 * Created by Chen on 2017/6/9.
 * 功能描述：
 */

public class ShareDialog extends BaseBottomDialog implements View.OnClickListener {
    private String ref_id;
    private String ref_type;
    private IWXAPI wxapi;

    public ShareDialog() {

    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_share;
    }

    @Override
    public void bindView(View v) {
        v.findViewById(R.id.ly_share_dx).setOnClickListener(this);
        v.findViewById(R.id.ly_share_qq).setOnClickListener(this);
        v.findViewById(R.id.ly_share_qonze).setOnClickListener(this);
        v.findViewById(R.id.ly_share_wechat).setOnClickListener(this);
        v.findViewById(R.id.ly_share_pyq).setOnClickListener(this);
    }

    @Override
    public float getDimAmount() {
        return 0.5f;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public String getRef_id() {
        return ref_id;
    }

    public void setRef_id(String ref_id) {
        this.ref_id = ref_id;
    }

    public String getRef_type() {
        return ref_type;
    }

    public void setRef_type(String ref_type) {
        this.ref_type = ref_type;
    }

    public void setShareInfo(String ref_id, String ref_type) {
        this.ref_id = ref_id;
        this.ref_type = ref_type;
    }

    @Override
    public void onClick(View v) {
        if (TextUtils.isEmpty(ref_id) && TextUtils.isEmpty(ref_type)) {
            Toast.makeText(getContext(), "分享内容为空", Toast.LENGTH_SHORT).show();
            return;
        }
        getShareContent(v.getId());
    }

    private void getShareContent(int id) {
        CommentRequest.shareContent(ref_id, ref_type, new CommentRequest.OnLoadSuccessListener<ShareEntity>() {
            @Override
            public void onSuccess(ShareEntity entity) {
                //微信接入
                wxapi = WXAPIFactory.createWXAPI(getContext(), APP_WX_ID, true);
                wxapi.registerApp(APP_WX_ID);
                switch (id) {
                    case R.id.ly_share_dx:
                        shareContentToDx(entity);
                        break;
                    case R.id.ly_share_wechat:
                        shareContentToWX(entity);
                        break;
                    case R.id.ly_share_pyq:
                        shareContentToPyq(entity);
                        break;
                }
            }

            @Override
            public void onFailure(ApiException e) {
                Toast.makeText(getContext(), "分享失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void shareContentToPyq(ShareEntity entity) {
        if (wxapi != null && wxapi.isWXAppInstalled() && isSupportWX()) {
            String smsBody = entity.getData().getTitle() + "       " + entity.getData().getContent() + "       " + "地址：" + entity.getData().getUrl();
            shareText(smsBody, SendMessageToWX.Req.WXSceneTimeline);
        } else {
            Toast.makeText(getContext(), "当前手机未安装微信", Toast.LENGTH_SHORT).show();
        }
    }

    private void shareContentToWX(ShareEntity entity) {
        if (wxapi != null && wxapi.isWXAppInstalled() && isSupportWX()) {
            String smsBody = entity.getData().getTitle() + "       " + entity.getData().getContent() + "       " + "地址：" + entity.getData().getUrl();
            shareText(smsBody, SendMessageToWX.Req.WXSceneSession);
        } else {
            Toast.makeText(getContext(), "当前手机未安装微信", Toast.LENGTH_SHORT).show();
        }
    }

    private void shareContentToDx(ShareEntity entity) {
        String smsBody = entity.getData().getTitle() + "       " + entity.getData().getContent() + "       " + "地址：" + entity.getData().getUrl();
        Uri smsToUri = Uri.parse("smsto:");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
        //短信内容
        sendIntent.putExtra("sms_body", smsBody);
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivityForResult(sendIntent, 1002);
    }

    //判断是否支持转发到朋友圈
//微信4.2以上支持，如果需要检查微信版本支持API的情况， 可调用IWXAPI的getWXAppSupportAPI方法,0x21020001及以上支持发送朋友圈
    public boolean isSupportWX() {
        int wxSdkVersion = wxapi.getWXAppSupportAPI();
        return wxSdkVersion >= 0x21020001;
    }

    /**
     * 分享文字到朋友圈或者好友
     *
     * @param text  文本内容
     * @param scene 分享方式：好友还是朋友圈
     */
    public boolean shareText(String text, int scene) {
        //初始化一个WXTextObject对象，填写分享的文本对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = text;
        return share(textObj, text, scene);
    }

    /**
     * 分享图片到朋友圈或者好友
     *
     * @param bmp   图片的Bitmap对象
     * @param scene 分享方式：好友还是朋友圈
     */
    public boolean sharePic(Bitmap bmp, int scene) {
        //初始化一个WXImageObject对象
        WXImageObject imageObj = new WXImageObject(bmp);
        //设置缩略图
        Bitmap thumb = Bitmap.createScaledBitmap(bmp, 60, 60, true);
        bmp.recycle();
        return share(imageObj, bmp, scene);
    }

    /**
     * 分享网页到朋友圈或者好友，视频和音乐的分享和网页大同小异，只是创建的对象不同。
     * 详情参考官方文档：
     * https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317340&token=&lang=zh_CN
     *
     * @param url         网页的url
     * @param title       显示分享网页的标题
     * @param description 对网页的描述
     * @param scene       分享方式：好友还是朋友圈 朋友圈，scene = SendMessageToWX.Req.WXSceneTimeline；好友， scene = SendMessageToWX.Req.WXSceneSession。
     */
    public boolean shareUrl(String url, String title, Bitmap thumb, String description, int scene) {
        //初试话一个WXWebpageObject对象，填写url
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = url;
        return share(webPage, title, thumb, description, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, Bitmap thumb, int scene) {
        return share(mediaObject, null, thumb, null, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, String description, int scene) {
        return share(mediaObject, null, null, description, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, String title, Bitmap thumb, String description, int scene) {
        //初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(mediaObject);
        if (title != null) {
            msg.title = title;
        }
        if (description != null) {
            msg.description = description;
        }
        if (thumb != null) {
            msg.thumbData = bmpToByteArray(thumb, true);
        }
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = scene;
        return wxapi.sendReq(req);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CommentRequest.cancelRequest();
    }
}
